package com.hainatong.jcmvvmbase.mainhome;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hainatong.jcmvvmbase.R;
import com.hainatong.jcmvvmbase.databinding.ActivityWebviewBinding;
import com.hainatong.mvvmbase.base.BaseMvvmActivity;
import com.hainatong.mvvmbase.base.NoViewModel;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.*;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;

public class WebViewActivity extends BaseMvvmActivity<ActivityWebviewBinding, NoViewModel>
{
    private static String URL_TAG = "WEB_URL";

    private String mUrl;

    public static void start(Activity mContext, String url)
    {
        if(StringUtils.isEmpty( url ))
        {
            start(mContext,null,false);
        }
        else
        {
            Bundle bundle = new Bundle();
            bundle.putString(URL_TAG , url);
            start(mContext,bundle,false);
        }

    }
    public static void start(Activity mContext, Bundle bundle, boolean isFinish)
    {
        Intent intent = new Intent();
        intent.setClass(mContext, WebViewActivity.class);
        if (bundle != null)
            intent.putExtra(mContext.getPackageName(), bundle);
        mContext.startActivity(intent);
        if (isFinish)
        {
            mContext.finish();
        }
    }

    public Bundle getBundle()
    {
        if (getIntent() != null && getIntent().hasExtra(getPackageName()))
            return getIntent().getBundleExtra(getPackageName());
        else
            return null;
    }

    @Override
    protected int getLayoutId()
    {
        return R.layout.activity_webview;
    }

    @Override
    protected int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initView()
    {
        Bundle mBundle = getBundle();
        if( mBundle != null )
        {
            mUrl = mBundle.getString(URL_TAG,"");
            LogUtils.eTag("WebViewActivity" , mUrl );
        }
        setToolbarTitle(viewDataBinding.includeTitle.toolbar,"百度百度百度百度百度百度百度百度百度百度百度百度百度百度百度百度");
        setToolBar(viewDataBinding.includeTitle.toolbar);



    }

    @Override
    protected void initData()
    {
        viewDataBinding.progressbar.setVisibility(View.VISIBLE);

        viewDataBinding.webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("copy://"))
                {
                    String content = url.substring("copy://".length());
                    if (!TextUtils.isEmpty(content))
                    {
                        //copy(content);
                    }
                }
                else
                {
                    view.loadUrl(url);
                }


                try {
                    if(url.startsWith("luban://") )
                    {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return false;
                }

                //处理http和https开头的url
                view.loadUrl(url);

                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                setToolbarTitle(viewDataBinding.includeTitle.toolbar,view.getTitle());
                setToolBar(viewDataBinding.includeTitle.toolbar);
            }
        });

        viewDataBinding.webview.setWebChromeClient(new WebChromeClient()
        {
            @Override
            public void onProgressChanged(WebView view, int newProgress)
            {
                if (newProgress == 100)
                {
                    viewDataBinding.progressbar.setVisibility(View.GONE);
                }
                else
                {
                    viewDataBinding.progressbar.setVisibility(View.VISIBLE);
                    viewDataBinding.progressbar.setProgress(newProgress);
                }
            }

            // For Android >= 5.0
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {

                //Intent intent = fileChooserParams.createIntent();
                //startActivityForResult(intent, CHOOSE_ANDROID_5);
                return true;
            }

        });

        WebSettings webSettings = viewDataBinding.webview.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowFileAccess(true);
//        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(false);
        webSettings.setSupportMultipleWindows(true);

        //        打开页面时， 自适应屏幕：
        webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放 将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setDomStorageEnabled(true); //不设置此 无法加载h5
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  //支持js调用window.open方法

        viewDataBinding.webview.getSettings().setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            viewDataBinding.webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //"https://www.iqiyi.com"
        mUrl = "file:///android_asset/web/useragreement.html";

        viewDataBinding.webview.loadUrl(mUrl);

    }

    @Override
    protected void onRetryBtnClick()
    {

    }

    private void setToolbarTitle(Toolbar toolbar, String title)
    {
        //toolbar.setBackgroundColor(ContextCompat.getColor(this,R.color.red));

        ((TextView)toolbar.findViewById(R.id.tv_title)).setText( title );
        ((ImageButton)toolbar.findViewById(R.id.btn_back)).setImageResource(R.drawable.svg_back);
        toolbar.findViewById(R.id.btn_back).setOnClickListener( v -> {
            supportFinishAfterTransition();
        } );
    }


}
